import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "../store/index"

Vue.use(VueRouter)
// 封装用户权限
function nextRouter(path,next){
  // 能去的路由地址
  let routerArr = store.state.user.menus_url
  // 判断权限中是否包含menu，如果包含menu才能next，如果不包含menu就让你进到首页
  if(routerArr.includes(path)){
    next()
  }else{
    next("/")
  }
}

export const secondRouter = [{
  path:"menu",
  meta:{
    title:"菜单管理"
  },
  beforeEnter:(to,from,next)=>{
    nextRouter("/menu",next)
  },
  component: ()=> import("../page/menu/menu.vue")
},{
  path:"role",
  meta:{
    title:"角色管理"
  },
  beforeEnter:(to,from,next)=>{
    nextRouter("/role",next)
  },
  component: ()=> import("../page/role/role.vue")
},{
  path:"manage",
  meta:{
    title:"管理员管理"
  },
  beforeEnter:(to,from,next)=>{
    nextRouter("/manage",next)
  },
  component: ()=> import("../page/manage/manage.vue")
},{
  path:"cate",
  meta:{
    title:"商品分类"
  },
  beforeEnter:(to,from,next)=>{
    nextRouter("/cate",next)
  },
  component: ()=> import("../page/cate/cate.vue")
},{
  path:"specs",
  meta:{
    title:"商品规格"
  },
  beforeEnter:(to,from,next)=>{
    nextRouter("/specs",next)
  },
  component: ()=> import("../page/specs/specs.vue")
},{
  path:"goods",
  meta:{
    title:"商品管理"
  },
  beforeEnter:(to,from,next)=>{
    nextRouter("/goods",next)
  },
  component: ()=> import("../page/goods/goods.vue")
},{
  path:"member",
  meta:{
    title:"会员管理"
  },
  beforeEnter:(to,from,next)=>{
    nextRouter("/member",next)
  },
  component: ()=> import("../page/member/member.vue")
},{
  path:"banner",
  meta:{
    title:"轮播图管理"
  },
  beforeEnter:(to,from,next)=>{
    nextRouter("/banner",next)
  },
  component: ()=> import("../page/banner/banner.vue")
},{
  path:"seckill",
  meta:{
    title:"秒杀活动"
  },
  beforeEnter:(to,from,next)=>{
    nextRouter("/seckill",next)
  },
  component: ()=> import("../page/seckill/seckill.vue")
}]


const routes = [{
  path:"/login",
  component: ()=> import("../page/login/login.vue")
},{
  path:"/",
  component: ()=> import("../page/index/index.vue"),
  children:[{
    path:"",
    component: ()=> import("../page/home/home.vue")
  },
  ...secondRouter
  ]
}]

const router = new VueRouter({
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
console.log(from);
  // 1、如果去的是登录页，直接next放行
  if(to.path == "/login"){
    next()
    return
  }
  // 2、如果去的不是登录页，你已经登录了，那么也next放行
  if(store.state.user.token){
    next()
    return
  }
// 3、说明你去的不是登录页并且也没登录，我们就给你定到登录页
  next("/login")
})
export default router